package com.bluefox.modules.common.controller;

import com.bluefox.annotation.AnonymousAccess;
import com.bluefox.config.FileProperties;
import com.bluefox.modules.common.service.upload.proxy.FileUploadProxy;
import com.bluefox.utils.FileUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: bluefox-parent
 * @description:  通用图片，视频上传接口
 * @author: Sun Feng
 * @create: 2020-06-30 15:31
 **/
@Slf4j
@RestController
@RequestMapping("/common/file")
@AllArgsConstructor
public class CommonController {

    private final FileUploadProxy fileUploadProxy;

    private final FileProperties fileProperties;

    /**
     *  这个文件上传为上传到fastDFS和OOS的
     * @param file
     * @return
     * @throws IOException
     */
    @AnonymousAccess
    @PostMapping(value = "/upload")
    public ResponseEntity<String> upload(MultipartFile file) throws IOException {
        String upload = fileUploadProxy.upload(file, StringUtils.getFilenameExtension(file.getOriginalFilename()));
        return new ResponseEntity<>(upload, HttpStatus.OK) ;
    }

    /**
     *  实现文件上传到本地服务器
     * @param file
     * @return
     * @throws IOException
     */
    @AnonymousAccess
    @PostMapping(value = "/localUpload")
    public ResponseEntity localUpload(@RequestParam("file") MultipartFile file) throws IOException {

        if (file.isEmpty()) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        // 上传文件基础路径
        String filePath = fileProperties.getPath().getPath();

        // 上传并返回新文件名称
        String fileName = FileUtil.upload(filePath, file);

        HashMap<String, Object> map = new HashMap<>(3);
        map.put("fileName",fileName);
        return new ResponseEntity<>(map, HttpStatus.OK) ;
    }
}
